import importlib
import sys
from docx import Document
from openpyxl import load_workbook
from datetime import datetime
import os.path


def ex2wo():
    importlib.reload(sys)

    # 读取excel文件:111.xlsx

    # 常见的图像缩放操作：
    # 打开
    dir_path = os.path.join(".", "file")
    file_path = os.path.join(dir_path,  '333.xlsx')
    wb = load_workbook(filename=file_path)
    # word文档
    document = Document()
    # 添加world标题
    document.add_heading('从excel读取的数据', 0)
    # 要读取多少列
    maxCols = 3
    # 创建一个0行maxCols列的表格
    table = document.add_table(rows=0, cols=5)
    # 获取所有表名
    sheetnames = wb.sheetnames
    # 取第1张表
    ws = wb[sheetnames[0]]
    # 循环读取excel中每行的内容写入word
    for row in ws.rows:
        # world表格中增加一行
        row_cells = table.add_row().cells
        row_cells[0].text = str(row[0].value)
        if row[1].value == '题目':
            row_cells[1].text = str(row[1].value)
        else:
            arr = str(row[1].value).split('\n')
            for i in range(arr.__len__()):
                row_cells[i + 1].text = str('%s - %s' % (arr[i], row[2].value[i]))

    # 结束world的写入并存储
    document.add_page_break()
    document.save(os.path.join(dir_path, '333-%s.docx' % datetime.now().strftime('%Y%m%d%H%M%S')))


if __name__ == '__main__':
    ex2wo()
